package com.demo.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.demo.beans.*;
import com.demo.controller.BaseAction;
import com.demo.mapper.demo.MenuMapper;
import com.demo.mapper.demo.PermissionMapper;
import com.demo.service.MenuService;
import com.demo.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public void recordClick(String menuAction, String userId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("menu_action", menuAction);
        Menu menu = menuMapper.selectOne(wrapper);
        Date date = new Date();
        int oldCount = menu.getClickCount();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String updateTime = dateFormat.format(date);
        /*User user = UserThreadLocal.get();
        String userId = user.getUserId();*/
        menu.setClickCount(oldCount + 1);
        menu.setLastClickTime(updateTime);
        menu.setLastClickUserid(userId);
        menuMapper.recordClick(menu);
    }

    @Override
    public ReturnData getMenuList(Menu menu) {
        ReturnData returnData = BaseAction.createReturnData();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("is_parent",0);
        if (StringUtils.isNotEmpty(menu.getMenuId())){
            wrapper.eq("menu_id",menu.getMenuId());
        }
        if (StringUtils.isNotEmpty(menu.getMenuName())){
            wrapper.eq("menu_name",menu.getMenuName());
        }
        if (StringUtils.isNotEmpty(menu.getParentId())){
            wrapper.eq("parent_id",menu.getParentId());
        }
        List<Menu> list = menuMapper.selectList(wrapper);
        Integer menuCount = menuMapper.selectCount(wrapper);
        if (list.size() > 0){
            returnData.put("returnCode","0000");
            returnData.put("returnMsg","查询成功");
            returnData.put("bean",list);
            returnData.put("count",menuCount);
        }else {
            returnData.put("returnCode","9999");
            returnData.put("returnMsg","查询失败，未查询到菜单信息！");
        }
        return returnData;
    }

    @Override
    public ReturnData insertMenu(Menu menu) {
        ReturnData returnData = BaseAction.createReturnData();
        String menuID = RedisUtil.getId("menu", redisTemplate);
        menuID = "C" + menuID;
        menu.setMenuId(menuID);
        menu.setIsParent(0);
        menu.setState(1);
        menu.setMenuEnName(menu.getMenuAction());
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String createTime = dateFormat.format(date);
        menu.setCreateTime(createTime);
        menu.setClickCount(0);
        int insert = menuMapper.insertMenu(menu);
        if (insert > 0){
            returnData.put("returnCode","0000");
            returnData.put("returnMsg","新增菜单成功");
        }else {
            returnData.put("returnCode","0000");
            returnData.put("returnMsg","新增菜单失败");
        }
        return returnData;
    }

    @Override
    public ReturnData queryMenuPermission(String userId) {
        ReturnData returnData = BaseAction.createReturnData();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("state",1);
        wrapper.eq("is_parent",0);
        List<Menu> menuList = menuMapper.selectList(wrapper);
        List<MenuPermissionVo> menuPermissionList = new ArrayList<>();
        for (Menu menu : menuList) {
            MenuPermissionVo build = MenuPermissionVo.builder().menuName(menu.getMenuName()).userId(userId).menuId(menu.getMenuId()).isParent(menu.getIsParent()).parentId(menu.getParentId()).build();
            menuPermissionList.add(build);
        }

        QueryWrapper permission = new QueryWrapper();
        permission.eq("user_id",userId);
        List<Permission> permissionList = permissionMapper.selectList(permission);
        for (Permission permission1 : permissionList) {
            for (MenuPermissionVo menuPermissionVo : menuPermissionList) {
                if (permission1.getMenuId() .equals(menuPermissionVo.getMenuId())){
                    menuPermissionVo.setPermission(1);
                }
            }
        }
        returnData.put("returnCode","0000");
        returnData.put("returnMsg","查询成功");
        returnData.put("bean",menuPermissionList);
        returnData.put("userId",userId);
        return returnData;
    }

    @Override
    public ReturnData addMenuPermission(String userId, String menuIds) {
        ReturnData returnData = BaseAction.createReturnData();
        int insertCount = 0;
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String createTime = dateFormat.format(date);
        String[] menuId = menuIds.split(",");
        List<String> menuIdList = Arrays.asList(menuId);
        List<String> menuCollect = menuIdList.stream().filter(menuid -> ! menuid.startsWith("having-")).collect(Collectors.toList());
        if (menuCollect.size() <= 0){
            returnData.put("returnCode","9999");
            returnData.put("returnMsg","选择的权限该用户已拥有，无需添加！");
            return returnData;
        }
        QueryWrapper<Menu> wrapper = new QueryWrapper();
        wrapper.in("menu_id", menuCollect);
        List<Menu> menus = menuMapper.selectList(wrapper);
        Set<String> parentIds = new TreeSet<>();
        for (Menu menu : menus) {
            parentIds.add(menu.getParentId());
        }
        List<Permission> permissions = new ArrayList<>();
        QueryWrapper<Permission> perentPw = null;
        for (String parentId : parentIds) {
            perentPw = new QueryWrapper();
            perentPw.eq("menu_id",parentId);
            perentPw.eq("user_id",userId);
            List<Permission> ppermission = permissionMapper.selectList(perentPw);
            if (ppermission.size() <= 0){
                Permission permission = new Permission();
                permission.setId(RedisUtil.getId("permission",redisTemplate));
                permission.setMenuId(parentId);
                permission.setUserId(userId);
                permission.setCreateTime(createTime);
                permissions.add(permission);
            }
        }
        for (String s : menuCollect) {
            Permission permission = new Permission();
            permission.setId(RedisUtil.getId("permission",redisTemplate));
            permission.setMenuId(s);
            permission.setUserId(userId);
            permission.setCreateTime(createTime);
            permissions.add(permission);
        }
        for (Permission permission : permissions) {
            int insert = permissionMapper.insert(permission);
            insertCount += insert;
        }
        returnData.put("returnCode","0000");
        returnData.put("returnMsg","成功为用户" + userId + "添加" + insertCount + "个菜单的权限");
        return returnData;
    }

    @Override
    public ReturnData queryMenuDetail(Menu menu) {
        ReturnData returnData = BaseAction.createReturnData();
        String menuId = menu.getMenuId();
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("menu_id",menuId);
        Menu menu1 = menuMapper.selectOne(wrapper);
        if (ObjectUtil.isNotEmpty(menu1)){
            returnData.put("returnCode","0000");
            returnData.put("returnMsg","查询成功");
            returnData.put("bean",menu1);
            return returnData;
        }
        return null;
    }

    @Override
    public ReturnData updateMenu(Menu menu) {
        ReturnData returnData = BaseAction.createReturnData();
//        int i = menuMapper.updateMenu(menu);
        /*UpdateWrapper<Menu> wrapper = new UpdateWrapper<>();
        if (StringUtils.isNotEmpty(menu.getMenuName())){
            wrapper.set("menu_name",menu.getMenuName());
        }
        if (StringUtils.isNotEmpty(menu.getMenuAction())){
            wrapper.set("menu_action",menu.getMenuAction());
        }
        if (ObjectUtil.isNotEmpty(menu.getMenuSort())){
            wrapper.set("menu_sort",menu.getMenuSort());
        }
        int update = menuMapper.update(menu, wrapper);
        int i = menuMapper.updateById(menu);*/
        int i = menuMapper.updateMenu(menu);
        if (i > 0){
            returnData.put("returnCode","0000");
        }
        return returnData;
    }
}
